import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {RoomobjModel} from '../roomobj.model';
import {ConfirmationService, TreeNode} from 'primeng/primeng';
import {ActivatedRoute, Router} from '@angular/router';
import {PublicService} from '../../services/public.service';
import {MessageService} from 'primeng/components/common/messageservice';
import {BasePage} from '../../base.page';
import {EventBusService} from "../../services/event-bus.service";

@Component({
  selector: 'app-cap-module',
  templateUrl: './cap-module.component.html',
  styleUrls: ['./cap-module.component.scss']
})
export class CapModuleComponent extends BasePage implements OnInit {
    title: string = '新增模块间';
    myForm: FormGroup;
    roomObj: RoomobjModel;
    types: Array<object>;
    displayRoom: boolean;
    displayManagements: boolean;
    displayDefault: boolean;
    displayPowerOrFacility: boolean;
    treeDatas: TreeNode[];
    selectedRoom;
    paramDid: string;

    constructor(private fb: FormBuilder,
                private router: Router,
                private activedRouter: ActivatedRoute,
                private publicService: PublicService,
                public messageService: MessageService,
                private eventBusService: EventBusService,
                public confirmationService: ConfirmationService) {
        super(confirmationService, messageService);
    }

    ngOnInit() {
        this.initForm();
        this.roomObj = new RoomobjModel();
        this.initType();
        this.initDatas();
        this.initDisplay();
        this.roomObj.availability_level = 'A';
        this.getRouterParam();
        this.getFather();
    }
    initForm(): void {
        this.myForm = this.fb.group({
            father: '',
            name: '',
            planning_power: '',
            planning_refrigerating_capacity: '',
            ups_power: '',
            planning_rack: '',
            planning_network_port: '',
            planning_network_bandwidth: '',
            area: '',
            room_manager: '',
            room_manager_phone: ''
        });
    }
    goBack() {
        this.router.navigate(['../../capacityBasalDatas'], {relativeTo: this.activedRouter});
    }
    initDisplay(): void {
        this.displayRoom = false;
        this.displayManagements = false;
        this.displayDefault = true;
        this.displayPowerOrFacility = false;
    }
    initType(): void {
        this.types = [
            {label: '普通机房', value: 'common'},
            {label: '模块化机房', value: 'module'},
            {label: '微模块机房', value: 'micmodule'},
            {label: '空调间', value: 'air'},
            {label: '电力间', value: 'power'},
            {label: '设施间', value: 'facility'},
        ];
        this.roomObj.room_type = this.types[2]['label'];
    }
    onHide(type): void {
        (type === 'room') && (this.displayRoom = false);
        (type === 'managements') && (this.displayManagements = false);
    }
    show(type): void {
        if (type === 'room') {
            this.displayRoom = true;
            this.initTreeNode();
        }
        (type === 'managements') && (this.displayManagements = true);
    }
    clear(type) {
        if (type === 'room') {
            this.roomObj.father_did = '';
            this.roomObj.father = '';
        }
        if (type === 'managements') {
            this.roomObj.room_manager = '';
            this.roomObj.room_manager_phone = '';
            this.roomObj.room_manager_pid = '';
        }
    }
    hide(type): void {
        this.onHide(type);
    }
    sure(type): void {
        this.onHide(type);
        this.roomObj['father'] = this.selectedRoom['label'];
        this.roomObj['father_did'] = this.selectedRoom['did'];
    }
    initDatas() {
        this.activedRouter.queryParams.subscribe(param => {
            if (param['did']) {
                this.title = '编辑模块间信息';
                this.publicService.getSingleNode(param['did']).subscribe(res => {
                    this.roomObj = new RoomobjModel(res);
                    this.roomObj.availability_level = res['availability_level'];
                    this.roomObj.room_type = res['room_type'];
                    if (res['room_type'] === '电力间' || res['room_type'] === '设施间'){
                        this.displayDefault = false;
                        this.displayPowerOrFacility = true;
                    }
                });
            }
        });
    }
    onFocus() {
        if (this.roomObj.room_type === 'power' || this.roomObj.room_type === 'facility') {
            this.displayPowerOrFacility = true;
            this.displayDefault = false;
            this.roomObj.availability_level = '';
        }else {
            this.displayDefault = true;
            this.displayPowerOrFacility = false;
        }
    }
    save() {
        this.roomObj.room_type = 'micmodule';
        if (this.roomObj.room_type === '电力间' || this.roomObj.room_type === '设施间' || this.roomObj.room_type === 'power' || this.roomObj.room_type === 'facility') {
            if (this.roomObj['name'] &&
                this.roomObj['father'] &&
                this.roomObj['planning_power'] &&
                this.roomObj['area'] &&
                this.roomObj['room_manager'] &&
                this.roomObj['room_manager_phone']  ) {
                if (this.paramDid) {
                    this.editRoomOrModule();
                }else {
                    this.addRoomOrModule();
                }
            }else {
                this.setValidators();
                this.alert('请填写完整信息', 'warn');
            }
        }else {
            if (this.roomObj['name'] &&
                this.roomObj['father'] &&
                this.roomObj['planning_power'] &&
                this.roomObj['planning_refrigerating_capacity'] &&
                this.roomObj['area'] &&
                this.roomObj['ups_power'] &&
                this.roomObj['planning_rack'] &&
                this.roomObj['planning_network_port'] &&
                this.roomObj['planning_network_bandwidth'] &&
                this.roomObj['room_manager'] &&
                this.roomObj['room_manager_phone']  ) {
                if (this.paramDid) {
                    this.editRoomOrModule();
                }else {
                    this.addRoomOrModule();
                }
            }else {
                this.setValidators();
                this.alert('请填写完整信息', 'warn');
            }
        }


    }
    editRoomOrModule() {
        this.publicService.editRoomOrModule(this.roomObj).subscribe(res => {
            if (res === '00000') {
                this.alert('编辑成功');
                this.router.navigate(['../../capacityBasalDatas'], { relativeTo: this.activedRouter});
                this.eventBusService.space.next(true);
            } else {
                this.alert(`编辑失败: ${res}`, 'error');
            }
        });
    }
    addRoomOrModule() {
        this.publicService.addRoomOrModule(this.roomObj).subscribe(res => {
            if (res === '00000') {
                this.alert('新增成功');
                this.eventBusService.space.next(true);
                this.router.navigate(['../../capacityBasalDatas'], {queryParams: {did: this.roomObj['father_did']}, relativeTo: this.activedRouter});
            }else {
                this.alert(`新增失败: ${res}`, 'error');
            }
        });
    }
    initTreeNode() {
        this.publicService.getCapBasalDatas('', this.roomObj.sp_type).subscribe(res => {
            this.treeDatas = res;
        });
    }
    get father() {
        return this.myForm.controls['father'].untouched && this.myForm.controls['father'].hasError('required');
    }
    get name() {
        return this.myForm.controls['name'].untouched && this.myForm.controls['name'].hasError('required');
    }
    get planning_power() {
        return this.myForm.controls['planning_power'].untouched && this.myForm.controls['planning_power'].hasError('required');
    }
    get planning_refrigerating_capacity() {
        return this.myForm.controls['planning_refrigerating_capacity'].untouched && this.myForm.controls['planning_refrigerating_capacity'].hasError('required');
    }
    get area() {
        return this.myForm.controls['area'].untouched && this.myForm.controls['area'].hasError('required');
    }
    get ups_power() {
        return this.myForm.controls['ups_power'].untouched && this.myForm.controls['ups_power'].hasError('required');
    }
    get planning_rack() {
        return this.myForm.controls['planning_rack'].untouched && this.myForm.controls['planning_rack'].hasError('required');
    }
    get planning_network_port() {
        return this.myForm.controls['planning_network_port'].untouched && this.myForm.controls['planning_network_port'].hasError('required');
    }
    get planning_network_bandwidth() {
        return this.myForm.controls['planning_network_bandwidth'].untouched && this.myForm.controls['planning_network_bandwidth'].hasError('required');
    }
    get room_manager() {
        return this.myForm.controls['room_manager'].untouched && this.myForm.controls['room_manager'].hasError('required');
    }
    get room_manager_phone() {
        return this.myForm.controls['room_manager_phone'].untouched && this.myForm.controls['room_manager_phone'].hasError('required');
    }
    dataEmitter(event) {
        this.roomObj.room_manager = event.name;
        this.roomObj.room_manager_pid = event.pid;
        this.roomObj.room_manager_phone = event.mobile;
    }
    displayEmitter(event) {
        this.displayManagements = event;
    }
    setValidators() {
        this.myForm.controls['name'].setValidators([Validators.required]);
        this.myForm.controls['father'].setValidators([Validators.required]);
        this.myForm.controls['planning_power'].setValidators([Validators.required]);
        this.myForm.controls['planning_refrigerating_capacity'].setValidators([Validators.required]);
        this.myForm.controls['planning_network_bandwidth'].setValidators([Validators.required]);
        this.myForm.controls['ups_power'].setValidators([Validators.required]);
        this.myForm.controls['planning_rack'].setValidators([Validators.required]);
        this.myForm.controls['planning_network_port'].setValidators([Validators.required]);
        this.myForm.controls['area'].setValidators([Validators.required]);
        this.myForm.controls['room_manager'].setValidators([Validators.required]);
        this.myForm.controls['room_manager_phone'].setValidators([Validators.required]);

        this.myForm.controls['name'].updateValueAndValidity();
        this.myForm.controls['father'].updateValueAndValidity();
        this.myForm.controls['planning_power'].updateValueAndValidity();
        this.myForm.controls['planning_refrigerating_capacity'].updateValueAndValidity();
        this.myForm.controls['planning_network_bandwidth'].updateValueAndValidity();
        this.myForm.controls['ups_power'].updateValueAndValidity();
        this.myForm.controls['planning_rack'].updateValueAndValidity();
        this.myForm.controls['planning_network_port'].updateValueAndValidity();
        this.myForm.controls['area'].updateValueAndValidity();
        this.myForm.controls['room_manager'].updateValueAndValidity();
        this.myForm.controls['room_manager_phone'].updateValueAndValidity();
    }
    getFather() {
        this.activedRouter.queryParams.subscribe(param => {
            this.roomObj['father'] = param['father'];
            this.roomObj['father_did'] = param['father_did'];
            this.roomObj['sp_type'] = param['sp_type'];
        });
    }
    getRouterParam(){
        this.activedRouter.queryParams.subscribe(param => {
            this.paramDid = param['did'];
        });
    }
}
